package com.tucc.hello.leetcode.no1_400.no1_200.no61_80.no67;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.addBinary("11", "11"));
        System.out.println(solution.addBinary("11", "10"));
        System.out.println(solution.addBinary("11", "1"));
        System.out.println(solution.addBinary("11", "0"));

    }

    public String addBinary(String a, String b) {
        if(a.length() == 0 || "0".equals(a)){
            return b;
        }
        if(b.length() == 0 || "0".equals(b)){
            return a;
        }
        StringBuilder builder = new StringBuilder();
        int flag = 0;
        int index = 1;
        int al = a.length();
        int bl = b.length();
        int maxIndex = Math.max(al, bl);
        while(index <= maxIndex){
            int x = 0, y = 0;
            if(index <= al){
                x = a.charAt(al - index) - '0';
            }
            if(index <= bl){
                y = b.charAt(bl - index) - '0';
            }
            int sum = x + y + flag;
            flag = 0;
            if(sum > 1){
                flag = 1;
            }
            sum = sum % 2;
            index ++;
            builder.append(sum);
        }
        if(flag == 1){
            builder.append(flag);
        }
        return builder.reverse().toString();
    }

}
